// pages/search/search.js
var app = getApp();
import { hotKeyWord, search, cartplace, detailTwo } from '../../config/https';
const tool = require('../../config/tool.js');
import Dialog from '../../vant/dialog/dialog';
import Notify from '../../vant/notify/notify';
import Toast from '../../vant/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    keyword: '', //输入框内容
    isfocus: false, //是否聚焦输入
    isCart: false, //购物车弹窗
    isShowSpec: false, //规格选择弹窗
    shopCarInfo: {//设置在缓存的购物车信息
      totalPrice: 0, //购物车总价
      shopNum: 0, //购物车数量
      shoplist: [], //购物车列表
    },
    hotKey: [],//热门搜索
    historyKey: [] ,//历史搜索
  },

  // 初始化数据
  initData() {
    this.setData({
      isEmpty: true,
      loadMore: false, //加载中提示
      finished: false, //是否已经请求完全部数据
      page: 0, //页码
      pagesize: 10, //分类数量
      totalPage: null, //总页数
      listData: [], //列表数据
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  //页面数据
  init(index = 0) {
    this.setData({
      loadMore: true
    })
    search({
      page: ++this.data.page, //页码
      pagesize: this.data.pagesize, //每页的大小
      keyword: this.data.keyword, //搜索关键字
      user_id: app.globalData.user_id, //用户id
    }).then(res => {
      const listData = [...this.data.listData, ...res.item_list];
      this.setData({
        totalPage: res.totalPage,
        loadMore: false,
        isEmpty: false,
        finished: this.data.page < res.totalPage ? false : true,
        listData
      })
      // 停止下拉刷新
      wx.stopPullDownRefresh();
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  // 显示规格弹窗按钮
  showSpec(e) {
    let item_id = e.currentTarget.dataset.id;
    Toast.loading({
      mask: true,
      message: '请稍后...'
    });
    detailTwo({
      user_id: app.globalData.user_id,
      item_id
    }).then(res => {
      const shoplist = this.data.shopCarInfo.shoplist || [];
      console.time('渲染耗时')
      res.item_info.list.forEach((item, index) => {
        let mirror = {
          id: item.id, //规格id
          number: 0, //数量
          item_sku: item.guige, //规格参数
          item_id: item.item_id, //商品id
          item_inventory: item.inventory, //规格库存
          price: item.price, //规格价格
          title: res.item_info.title, //商品名称
          cate_id: res.item_info.cate_id, //分类id
        };
        shoplist.forEach(shopItem => {
          if (mirror.id === shopItem.id) {
            Object.assign(mirror, shopItem)
          }
        })
        res.item_info.list[index] = mirror;
      });
      Toast.clear();
      wx.hideTabBar();
      this.setData(Object.assign(res, { isShowSpec: true }));
      this.data.specInfo = this.deepClone(res.item_info.list);
      console.timeEnd('渲染耗时')
    })
  },
  specTap() {
    wx.showTabBar();
    this.setData({ isShowSpec: false })
  },
  specChange(e) {
    let index = e.currentTarget.dataset.index;
    this.data.specInfo[index].number = e.detail;
  },
  specaffirm() {
    let specInfo = this.data.specInfo;
    if (specInfo) {
      let shopCarInfo = this.data.shopCarInfo;
      specInfo.forEach(item => {
        let hasSameGoodsIndex = -1;
        for (var i = 0; i < shopCarInfo.shoplist.length; i++) {
          console.log(shopCarInfo.shoplist.length)
          var tamShopCarMap = shopCarInfo.shoplist[i];
          if (tamShopCarMap.id === item.id) {
            if (item.number > 0) {
              shopCarInfo.shoplist.splice(i, 1, item)
            }else{
              shopCarInfo.shoplist.splice(i, 1)
            }
            hasSameGoodsIndex = i;
            break
          }
        }
        if (hasSameGoodsIndex === -1 && item.number > 0) {
          shopCarInfo.shoplist.push(item);
        }
      })
      this.setCartList(shopCarInfo);
    }
    this.setData({ isShowSpec: false })
  },
  // 对象拷贝
  deepClone: function (obj) {
    let _obj = JSON.stringify(obj),
      objClone = JSON.parse(_obj);
    return objClone
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({ isCart: false });
    hotKeyWord().then(res => {
      this.setData({ hotKey: res.keyword || [] })
    })
    //加载缓存，取得搜索历史
    wx.getStorage({
      key: 'historyKey',
      success: res => {
        this.setData({
          historyKey: res.data,
        })
      }
    })
    //加载缓存，取得购物车信息
    wx.getStorage({
      key: 'shopCarInfo',
      success: res => {
        if (res.data.shoplist) {
          this.setData({
            shopCarInfo: res.data,
          })
        } else {
          wx.setStorage({
            key: "shopCarInfo",
            data: this.data.shopCarInfo
          })
        }
      }
    })
  },

  setCartList(list) {
    var shopCarInfo = this.data.shopCarInfo;
    const listData = this.data.listData;
    shopCarInfo.totalPrice = 0
    shopCarInfo.shopNum = 0
    if (list.shoplist.length == 0) {
      shopCarInfo = list
      listData.forEach((item) => { item.number = 0 })
    } else {
      list.shoplist.forEach((item, index) => {
        listData.forEach((_item) => {
          if (item.id === _item.id) {
            _item.number = item.number
          }
        })
        shopCarInfo.totalPrice += Math.floor(parseFloat(item.price) * item.number * 100) / 100;
        shopCarInfo.shopNum += item.number;
      })
    }
    this.setData({ shopCarInfo, listData })
    wx.setStorage({
      key: "shopCarInfo",
      data: shopCarInfo
    })
  },

  itemJiaTap(e) {
    let shopCarMap = e.currentTarget.dataset.info;
    var shopCarInfo = this.data.shopCarInfo;
    var hasSameGoodsIndex = -1;
    for (var i = 0; i < shopCarInfo.shoplist.length; i++) {
      var tamShopCarMap = shopCarInfo.shoplist[i];
      if (tamShopCarMap.id === shopCarMap.id) {
        shopCarMap.number++;
        hasSameGoodsIndex = i;
        break
      }
    }
    if (hasSameGoodsIndex > -1) {
      shopCarInfo.shoplist.splice(hasSameGoodsIndex, 1, shopCarMap)
    } else {
      shopCarMap.number++;
      shopCarInfo.shoplist.push(shopCarMap)
    }
    this.setCartList(shopCarInfo);
  },
  itemJianTap(e) {
    var shopCarInfo = this.data.shopCarInfo;
    const listData = this.data.listData;
    const shopCarMap = e.currentTarget.dataset.info;
    for (var i = 0; i < shopCarInfo.shoplist.length; i++) {
      var tamShopCarMap = shopCarInfo.shoplist[i];
      if (tamShopCarMap.id === shopCarMap.id) {
        shopCarMap.number--
        if (shopCarMap.number == 0) {
          for (var j = 0; j < listData.length; j++) {
            var tamlistData = listData[j];
            if (tamlistData.id === shopCarMap.id) {
              tamlistData.number = 0
              break
            }
          }
          shopCarInfo.shoplist.splice(i, 1)
        } else {
          shopCarInfo.shoplist.splice(i, 1, shopCarMap)
        }
        break
      }
    }
    this.setData({ listData })
    this.setCartList(shopCarInfo);
  },

  overlimit(e) {
    this.failNot(e.detail || '商品库存不足！')
  },

  //输入框失焦
  itemBlurTap(e) {
    let shopCarInfo = this.data.shopCarInfo;
    let listData = this.data.listData;
    let value = e.detail.detail.value;
    let shopCarMap = e.currentTarget.dataset.info;
    for (var i = 0; i < shopCarInfo.shoplist.length; i++) {
      var tamShopCarMap = shopCarInfo.shoplist[i];
      if (tamShopCarMap.id === shopCarMap.id) {
        shopCarMap.number = value
        if (shopCarMap.number == 0) {
          for (var j = 0; j < listData.length; j++) {
            var tamlistData = listData[j];
            if (tamlistData.id === shopCarMap.id) {
              tamlistData.number = 0
              break
            }
          }
          shopCarInfo.shoplist.splice(i, 1)
        } else {
          shopCarInfo.shoplist.splice(i, 1, shopCarMap)
        }
        break
      }
    }
    this.setData({ listData })
    this.setCartList(shopCarInfo);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  // 跳转商品详情
  toDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../detail/detail?item_id=${id}`,
    })
  },

  // 步进器改变
  onChange(e) {
    console.log(e)
  },

  // 购物车弹窗
  cartTap() {
    this.setData({
      isCart: !this.data.isCart, //购物车弹窗
    })
  },

  // 清空购物车
  clearCart() {
    Dialog.confirm({
      zIndex: 110,
      message: '确定要删除购物车全部商品吗？'
    }).then(() => {
      const shopCarInfo = {
        totalPrice: 0, //购物车总价
        shopNum: 0, //购物车数量
        shoplist: [], //购物车列表
      }
      wx.setStorage({
        key: "shopCarInfo",
        data: shopCarInfo
      })
      this.setData({ isCart: false })
      this.setCartList(shopCarInfo)
    }).catch(() => {
      // on cancel
    });
  },

  //删除单个购物车商品
  actionsTap(e) {
    var shopCarInfo = this.data.shopCarInfo;
    const listData = this.data.listData;
    const { index, id } = e.currentTarget.dataset;
    shopCarInfo.shoplist.splice(index, 1)
    for (var i = 0; i < listData.length; i++) {
      var tamlistData = listData[i];
      if (tamlistData.id === id) {
        tamlistData.number = 0
        break
      }
    }
    this.setData({
      listData,
      isCart: shopCarInfo.shoplist.length >= 1
    })
    this.setCartList(shopCarInfo);
  },

  // 下单
  toplace() {
    Toast.loading({
      mask: true,
      duration: 0,
      message: '请稍后...'
    });
    var shopCarInfo = this.data.shopCarInfo;
    var item_list = new Array;
    shopCarInfo.shoplist.forEach((item, index) => {
      item_list.push({
        id: item.item_id,
        sku_id: item.id,
        nums: item.number
      })
    })
    cartplace({
      user_id: app.globalData.user_id, //用户id
      item_list: JSON.stringify(item_list)
    }).then(res => {
      // const shopCarInfo = {
      //   totalPrice: 0, //购物车总价
      //   shopNum: 0, //购物车数量
      //   shoplist: [], //购物车列表
      // }
      // wx.setStorage({
      //   key: "shopCarInfo",
      //   data: shopCarInfo
      // })
      // this.setCartList(shopCarInfo)
      Toast.clear()
      wx.navigateTo({
        url: `../submit/submit?data=${JSON.stringify(res)}`,
      })
    }).catch(err => {
      Toast.clear()
      this.failNot(err)
    })
  },

  //点击搜索框时
  onsearchTap(){
    this.setData({
      isfocus: true
    })
  },

  //搜索框输入内容
  keywordTap(e){
    this.data.keyword = e.detail.value
  },

  //搜索框失焦
  searchBlurTap(){
    this.data.keyword || this.clearInput()
    this.setData({
      isfocus: false
    })
  },

  //搜索框聚焦
  searchFocusTap(){
    this.setData({
      isfocus: true
    })
  },

  //点击搜索按钮
  searchTap(){
    const keyword = this.data.keyword
    const historyKey = this.data.historyKey
    if (!tool.u_Reg(keyword, 'notEmpty')) {
      this.failNot("请输入要搜索的关键字!")
      return
    }
    if (historyKey.indexOf(keyword) < 0){
      historyKey.push(keyword)
      wx.setStorageSync('historyKey', historyKey)
    }
    this.setData({ keyword })
    this.initData()
    this.init()
  },
  // 清除输入框内容
  clearInput(){
    this.initData()
    //加载缓存，取得搜索历史
    const historyKey = wx.getStorageSync('historyKey')
    this.setData({
      keyword: '',
      historyKey
    })
  },

  //点击搜索历史
  historyKeyTap(e){
    const keyword = e.currentTarget.dataset.item
    this.setData({ keyword })
    this.initData()
    this.init()
  },

  //删除搜索记录
  deleteTap(){
    Dialog.confirm({
      message: '是否要清除历史搜索？'
    }).then(() => {
      this.setData({ historyKey: []})
      wx.setStorageSync('historyKey', [])
    }).catch(() => {
      // on cancel
    });
  },

  succNot(msg) {
    Notify({
      text: msg,
      backgroundColor: '#1989fa'
    });
  },

  failNot(msg) {
    Notify({
      text: msg,
      backgroundColor: '#f44'
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.finished && !this.data.loadMore) {
      this.init()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})